import { useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'

import Modal from './Modal'
import { DiaryAPI } from '../app/api'
import { FormField, Input, Textarea, Select, Switch } from './ui/Form'

const createInitialState = () => ({
  title: '',
  content: '',
  visibility: 'shared',
  notify: true,
  allowAISummary: true,
})

type DiaryComposerDialogProps = {
  open: boolean
  onClose: () => void
  entry?: {
    id: number
    title: string
    content_md: string
    mood: string | null
    tags: string[]
    visibility: string
  }
}

const DiaryComposerDialog = ({ open, onClose, entry }: DiaryComposerDialogProps) => {
  const queryClient = useQueryClient()
  const [form, setForm] = useState(() => createInitialState())
  const [error, setError] = useState<string | null>(null)

  // fill when editing
  useEffect(() => {
    if (entry && open) {
      setForm({
        title: entry.title || '',
        content: entry.content_md || '',
        visibility: entry.visibility || 'shared',
        notify: false,
        allowAISummary: true,
      })
    } else if (!entry && open) {
      setForm(createInitialState())
    }
  }, [entry, open])

  const createMutation = useMutation({
    mutationFn: DiaryAPI.create,
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['diary', 'list'] })
      setForm(createInitialState())
      onClose()
    },
  })

  const updateMutation = useMutation({
    mutationFn: (payload: Parameters<typeof DiaryAPI.update>[1]) => DiaryAPI.update(entry!.id, payload),
    onSuccess: async () => {
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['diary', 'list'] }),
        entry ? queryClient.invalidateQueries({ queryKey: ['diary', entry.id] }) : Promise.resolve(),
      ])
      onClose()
    },
  })

  const isValid = useMemo(
    () => form.content.trim().length > 0,
    [form.content],
  )

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const pending = entry ? updateMutation.isPending : createMutation.isPending
    if (!isValid || pending) return
    setError(null)

    const payload: any = {
      content_md: form.content.trim(),
      visibility: form.visibility,
      notify_partner: form.notify,
      allow_ai_summary: form.allowAISummary,
    }
    if (form.title.trim()) payload.title = form.title.trim()

    try {
      if (entry) {
        const { notify_partner, allow_ai_summary, ...rest } = payload
        await updateMutation.mutateAsync(rest)
      } else {
        await createMutation.mutateAsync(payload)
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : '保存失败，请稍后重试'
      setError(message)
    }
  }

  return (
    <Modal open={open} onClose={onClose} title={entry ? '编辑日记' : '创建新日记'}>
      <form className="space-y-4" onSubmit={handleSubmit}>
        <FormField label="标题 (可选)">
          <Input
            value={form.title}
            onChange={(e) => setForm((prev) => ({ ...prev, title: e.target.value }))}
            placeholder="记录甜蜜瞬间"
          />
        </FormField>
        <FormField label="内容" hint="支持 Markdown 简单语法">
          <Textarea
            value={form.content}
            onChange={(e) => setForm((prev) => ({ ...prev, content: e.target.value }))}
            placeholder="写下今天的故事与感受..."
          />
        </FormField>
        {/* 心情与标签由 AI 在后台自动提取与生成，这里不再手动填写 */}
        <div className="grid gap-3 sm:grid-cols-2">
          <FormField label="可见范围">
            <Select
              value={form.visibility}
              onChange={(e) => setForm((prev) => ({ ...prev, visibility: e.target.value }))}
            >
              <option value="shared">情侣空间</option>
              <option value="private">仅自己</option>
            </Select>
          </FormField>
          <div className="rounded-2xl border border-slate-200/70 bg-gradient-to-br from-white to-slate-50/60 px-4 py-3">
            <label className="flex items-center justify-between text-sm">
              <span>通知伴侣</span>
              <Switch checked={form.notify} onChange={(val) => setForm((p) => ({ ...p, notify: val }))} />
            </label>
            <label className="mt-3 flex items-center justify-between text-sm">
              <span>AI 自动摘要</span>
              <Switch
                checked={form.allowAISummary}
                onChange={(val) => setForm((p) => ({ ...p, allowAISummary: val }))}
              />
            </label>
          </div>
        </div>
        {error ? <p className="text-xs text-red-500">{error}</p> : null}
        <button
          type="submit"
          className="w-full rounded-full bg-gradient-to-r from-blush-500 to-lavender-500 px-6 py-3 text-sm font-semibold text-white shadow-card transition hover:shadow-lg disabled:cursor-not-allowed disabled:opacity-60"
          disabled={!isValid || createMutation.isPending || updateMutation.isPending}
        >
          {createMutation.isPending || updateMutation.isPending ? '保存中...' : '保存日记'}
        </button>
      </form>
    </Modal>
  )
}

export default DiaryComposerDialog
